package lumis.content.lock;

import java.util.ArrayList;
import java.util.List;

import lumis.content.ContentManagerFactory;
import lumis.content.core.ContentLocale;
import lumis.content.core.ContentVersion;
import lumis.content.core.LockType;
import lumis.content.table.ContentTableSource;
import lumis.doui.processaction.ProcessActionHandler;
import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;

/**
 * Class responsible for executing bulk lock/unlock.  It will first verify is all contents selected are in the 
 * same state (locked or unlocked) not verifying the lockType.  If they are unlocked, all selected contents will
 * go to the locked state, otherwise, all contents will be placed under unlocked state.  
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class ContentLockProcessActionHandler extends ProcessActionHandler<ContentTableSource>
{
	private static String LOCK = "lock";
	private static String UNLOCK = "releaseLock";

	public void processAction() throws PortalException
	{
		
		String[] ids = (String[]) getParameter(source.getPrimaryKeyField().getId());
		
		String lock = null;
		
		List<String> contentLocaleIds = new ArrayList<String>();
		
	 	for(String itemId : ids)
		{
			ContentVersion contentVersion = ContentManagerFactory.getContentManager().getContentVersionByItemId(itemId);
			ContentLocale contentLocale = contentVersion.getContentLocale();
			contentLocaleIds.add(contentLocale.getId());
			if(lock == null)
			{
				lock = getAction(contentLocale.getLockType());
			}
			if(!lock.equals(getAction(contentLocale.getLockType())))
			{
				throw new PortalException("STR_NOT_SAME_ACTION", this.getResource());
			}
		}
	 	
		try
		{
			for (String contentLocaleId : contentLocaleIds)
			{
				if(LOCK.equals(lock))
				{
					ContentManagerFactory.getContentManager().lock(contentLocaleId, LockType.EXPLICIT);
				}
				else
				{
					ContentManagerFactory.getContentManager().releaseLock(contentLocaleId);
				}
			}
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}
	
	private String getAction(LockType lockType){
		return (LockType.NONE.equals(lockType))?LOCK:UNLOCK;	
	}
}
